<?php

// @formatter:off
/**
 * @file rule.php
 * @author Alejandro Dario Simi
 * @date $Date: 2014-06-03 03:40:32 +0000 (Tue, 03 Jun 2014) $
 *
 * $Id: rule.php 112 2014-06-03 03:40:32Z daemonraco@gmail.com $
 * $URL: http://wcomix.googlecode.com/svn/trunk/services/rules/add/rule.php $
 */
// @formatter:on

class WCServiceRulesAddRule extends WCService {
	//
	// Protected variables.
	//
	// Class methods.
	public function __construct() {
		parent::__construct();

		$this->_readOnlyConflict = true;

		$this->_requiredParams["url"][] = "group";

		$this->_requiredParams["params"][] = "name";

		$this->_requiredPermissions["to"][] = WC_PERM_RULE_ADD;
	}
	//
	// Public methods
	public function check() {
		if(parent::check()) {
			global $wcGroup;

			if(!$this->name) {
				$this->setError(WC_HTTPERROR_INTERNAL_SERVER_ERROR, "No name specified");
			}
			if(!$wcGroup || !$wcGroup->ok()) {
				$this->setError(WC_HTTPERROR_INTERNAL_SERVER_ERROR, "There's something wrong with the specified group id");
			}
			if(WCRulesHolder::i()->itemByNameInGroup($this->name, $wcGroup)) {
				$this->setError(WC_HTTPERROR_BAD_REQUEST, "There's another rule using this name");
			}
		}

		return $this->ok();
	}
	//
	// Protected methods.
	public function load() {
		$out = false;

		if(parent::load()) {
			$this->name = isset($this->name) ? trim($this->name) : "";

			$out = true;
		}

		return $out;
	}
	protected function runPOST() {
		//
		// Loading global pointers.
		global $wcErrno;
		global $wcError;
		global $wcGroup;

		$rule = WCRulesHolder::I()->createInGroup($this->name, $wcGroup);
		if($rule && $rule->ok()) {
			$this->_results["id"] = $rule->id();
			$this->_results["name"] = $rule->name();
			$this->_count++;
		} else {
			$wcErrno = WC_HTTPERROR_INTERNAL_SERVER_ERROR;
			$wcError = "Unable to create rule '{$this->name}'";
			$this->setError($wcErrno, "[{$wcErrno}] {$wcError}", array(
				"errno" => $wcErrno,
				"error" => $wcError
			));
		}
	}
}
